
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

import com.hogofwar.DJbot.BasePlugin;
import com.hogofwar.DJbot.IRCBase;

public class COM_factoids implements BasePlugin {

	public void start(final IRCBase irc, final String[] extra, String channel,
			String sender, String hostname, boolean usename) {
		String start = "";
		if (usename == true) {
			start = sender + ": ";
		}
		if(extra.length==0){
			irc.sendNotice(sender,"The correct usage is: ;factoids [key] [data]");
		}else{
		String tosend = "Failed to save.";
		try {
			Class.forName("org.sqlite.JDBC");
			Connection conn = DriverManager
					.getConnection("jdbc:sqlite:factoids.db");
			Statement stat = conn.createStatement();
			// stat.executeUpdate("drop table if exists people;");
			stat.executeUpdate("create table IF NOT EXISTS factoids (key, message, time, user);");
			PreparedStatement prep = conn
					.prepareStatement("insert into factoids values (?, ?, ?, ?);");
			String key = extra[0];
			String rest = null;
			boolean istrue = true;
			for(String s: extra){
				if(istrue){
					istrue = false;
				}else{
					if(rest !=null)
						rest = rest+" "+s.trim();
					else
						rest = s.trim();
				}
			
			//System.out.println(substring);
			}
			//Calendar cal = new GregorianCalendar();
//			System.out.println(key);
//			System.out.println(rest);
//			System.out.println(System.currentTimeMillis());
//			System.out.println(sender);
			prep.setString(1, key.toLowerCase());
			prep.setString(2, rest);
			prep.setLong(3, System.currentTimeMillis());
			prep.setString(4, sender);
			prep.addBatch();

			conn.setAutoCommit(false);
			prep.executeBatch();
			conn.setAutoCommit(true);
			conn.close();
			IRCBase.factoidsset++;
			 tosend = "Saved Successfully!";
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			tosend = "Failed";
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			tosend = "Failed";
		}
		
	
		irc.sendNotice(sender, tosend);
		}
	}

	public String help() {
		return "Factoids - factoids [key] [message] - Sets the message to the key.";

	}

	public String version() {
		return "Factoids version 1";
		// TODO Auto-generated method stub

	}

	@Override
	public String restrict() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Boolean hide() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String aliases() {
		// TODO Auto-generated method stub
		return "rem, remember, r, set, fact";
	}

}